<template>
  <div>
    <Modal
      title="选择销售区域"
      :closable="false"
      :mask-closable="false"
      v-model="visible"
    >
      <Table
        ref="saleAreaTable"
        height="500"
        :columns="column"
        :data="saleAreaTableData"
        @on-selection-change="selectCity"
        @on-select-all="selectAllCity"
        @on-select-all-cancel="selectAllCancelCity"
      />
      <Row slot="footer" style="justify-content: center;">
        <Button type="primary" v-preventReClick @click="handleConfirm">确定</Button>
      </Row>
    </Modal>
  </div>
</template>

<script>

export default {
  props: {
    dialogVisible: {
      type: Boolean
    },
    saleCityList: {
      type: Array,
      default: function () {
        return []
      }
    },
    hasSelectCityList: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      saleAreaTableData: [],
      chooseAll: '',
      visible: false,
      column: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '城市',
          key: 'areaName',
          minWidth: 150
        },
      ],
    }
  },
  computed: {
    selectList () {
      return this.hasSelectCityList;
    },
  },
  watch: {
    dialogVisible (val) {
      this.visible = val;
      if (val) {
        // this.saleAreaTableData = this.saleCityList
        this.initSelectList()
      }
    }
  },

  methods: {
    initSelectList () {
      const setSaleData = []
      const hasSelectAreaCodes = this.hasSelectCityList.map(item => {
        if (item?.areaCode) return item.areaCode
        return item
      })
      this.saleAreaTableData = this.saleCityList.map(item => {
        const hasChecked = hasSelectAreaCodes.includes(item.areaCode)
        if (hasChecked) setSaleData.push(item)
        return { ...item, _checked: hasChecked }
      })
      this.setSale(setSaleData)
    },
    selectCity (e) {
      this.setSale(e)
    },

    selectAllCity (e) {
      this.chooseAll = '1'
    },

    selectAllCancelCity (e) {
      this.chooseAll = ''
    },

    setSale (data) {
      let params = { data, chooseType: this.chooseAll }
      this.$emit('set-sale-city', params)
    },

    handleConfirm () {
      this.$emit('select-area-confirm')
    }
  }
}
</script>
